import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Login from '@/views/Login.vue'
import welcome from '@/views/welcome/index.vue'
import ArticleList from '@/views/article/index.vue'
import MyChild from '@/assets/test/test.vue'
import ImageInfo from '@/views/images/image.vue'
import PublishArticle from '@/views/article/PublishArticle'
import Comment from '@/views/comment/index.vue'
import Fans from '@/views/fans/index.vue'
import Setting from '@/views/setting/index.vue'
Vue.use(VueRouter)

const routes = [
  // 路由重定向
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/home/welcome',
    children: [{
      path: 'welcome',
      component: welcome
    },
    {
      path: 'article',
      component: ArticleList
    },
    {
      path: 'images',
      component: ImageInfo
    },
    {
      path: 'publish',
      component: PublishArticle
    },
    {
      path: 'comment',
      component: Comment
    },
    {
      path: 'fans',
      component: Fans
    },
    {
      path: 'setting',
      component: Setting
    }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/test',
    name: 'test',
    component: MyChild
  }
]

const router = new VueRouter({
  routes
})
// 通过路由的导航守卫拦截所有的路由跳转
router.beforeEach((to, from, next) => {
  // to表示要跳转到哪里去
  // from表示是从哪里跳转过来
  // next 是一个方法用来实现跳转（执行next才能实现路由跳转）
  const token = localStorage.getItem('mytoken')
  // 当没有登录（没有token）并且跳转页不是登录页 就不让跳转  而是跳回登录页
  if (to.path !== '/login' && !token) {
    next('/login')
  } else {
    // 正常跳转
    next()
  }
})

export default router
